define(['app'], function(app) {
	'use strict';
	
	var controller = function controller($scope, Mybrowsing, $timeout, $ionicScrollDelegate,GoPage, Auth, GoDialog) {
		
		function init_scope() {
			$scope.data = {};
			$scope.data = {
				goods: {
					isend: false,
					cPage: 1, 
					tPage: 0,
					list: []
				}
			}
		}

		//画面加载
		$scope.$on('$ionicView.afterEnter', function(scope, status) {
			if (status.direction != 'back') {
				$scope.isLoad = false; //可以加载
				init_scope();
				$scope.init_page(true);
			} 
		}, false);


		/******************下拉刷新**************/
		$scope.doRefresh = function() {
			$scope.isLoad = true;
			$scope.init_page(true, 'refresh');
		};
		
		//加载更多
		$scope.doRefreshMore = function() {
			if ($scope.isLoad) return;
			$scope.isLoad = true;
			$scope.init_page(false, 'more');
		};
		/*******************下拉刷新**************/
		

		//初始化页面。  isInit：是否初始化，true初始化。   completeFlag：是上拉，还是下拉。
		$scope.init_page = function(isInit, completeFlag) {
			var data = $scope.data.goods;
			if (isInit) data.isend = false;

			var param = {
				pagelimit: 20,
				nPage: isInit ? 1 : (data.cPage - 0 + 1)//-0为了转为int
			};

			var fnFavo = Mybrowsing.get_goods;//商品的浏览记录
			fnFavo(param, function(res) {
				if (!res.success) {
					GoDialog.toast(res.msg);
					return;
				}
				data.cPage = res.result.page.cPage;//当前页
				data.tPage = res.result.page.tPage;
				var rltList = res.result.goods || [];
				$scope.count = res.result.page.count;//总数
//				console.log(res.result)
				if (data.cPage == data.tPage) data.isend = true;

				if (isInit) {
					data.list = rltList;
				} else {
					data.list = data.list.concat(rltList);
				}
			}, null, function() {
				if (completeFlag === 'refresh')	{//下拉
					$scope.$broadcast('scroll.refreshComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1500);
				}
				if (completeFlag === 'more') {//上拉，加载更多
					$scope.$broadcast('scroll.infiniteScrollComplete');
					$timeout(function() {
						$scope.isLoad = false;
					}, 1500);
				}
			})
		}

		//删除浏览记录
		$scope.delete_browsing = function(index, $event) {
			$event.stopPropagation();//阻止事件冒泡
			var data = $scope.data.goods;
			var param = {};
			param.goods_id = data.list[index].goods_id
			var fnFavo = Mybrowsing.delete_goods;
			fnFavo(param, function(res) {
				if (res.success) {
					GoDialog.toast("删除成功！");
					data.list.splice(index, 1);
					$scope.count -=1; 
				}else{
					GoDialog.toast(res.msg);
				}
			});
		}
		
		
		//页面跳转
		$scope.onshow_detail = function(goods_id) {
			GoPage.go_states("productdetail", { "goods_id": goods_id, "type": "goods" });
		};
		$scope.onshow_first = function(store_id,$event) {
			$event.stopPropagation();//阻止事件的冒泡
			GoPage.go_states("first", {"store_id": store_id});
		}
		
		
	}

	controller.$inject = ['$scope', 'Mybrowsing','$timeout', '$ionicScrollDelegate', 'GoPage', 'Auth', 'GoDialog'];
	
	return app.registerController("mybrowsingctrl",controller);
});